package cn.zhfeat.hatch.web.utils.merchant;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {
	public static String scrmbase = "http://tapi.cecook.cn/v1/crm";

	public static String httpPostWithJSON(String url, JSONObject jsonParam){
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");    
        entity.setContentType("application/json");    
        httpPost.setEntity(entity);
        try {
			HttpResponse resp = client.execute(httpPost);
			if(resp.getStatusLine().getStatusCode() == 200) {
			    HttpEntity he = resp.getEntity();
			    respContent = EntityUtils.toString(he,"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return respContent;
    }
	
	/** 
     * post请求 
     * @param url         url地址 
     * @return 
     * @throws URISyntaxException 
     * @throws HttpException
     */  
    public static String httpPost(String url) throws URISyntaxException, HttpException {
        //post请求返回结果  
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String str = "";  
        try {  
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");  
            /**请求发送成功，并得到响应**/  
            if (result.getStatusLine().getStatusCode() == 200) {  
                try {  
                    /**读取服务器返回过来的json字符串数据**/  
                    str = EntityUtils.toString(result.getEntity());
                } catch (Exception e) {  
                }  
            }  
        } catch (IOException e) {  
        }  
        return str;  
    }  
   
   
    /** 
     * 发送get请求 
     * @param url    路径 
     * @return 
     * @throws URISyntaxException 
     * @throws HttpException
     */  
    public static String httpGet(String url) throws URISyntaxException, HttpException {
        //get请求返回结果  
         String strResult = null;  
        try {  
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求  
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
   
            /**请求发送成功，并得到响应**/  
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {  
                /**读取服务器返回过来的json字符串数据**/  
                  strResult = EntityUtils.toString(response.getEntity());
            } else {  
            }  
        } catch (IOException e) {  
        }  
        return strResult;  
    }  
    
    public static String jsonPost(String strURL, Map<String, Object> params) {  
        return jsonPostByJson(strURL, FastJsonUtil.createJsonString(params));  
    }  
    
    public static String jsonPostByJson(String strURL, String jsonStr) {  
    	try {  
    		URL url = new URL(strURL);// 创建连接  
    		HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
    		connection.setDoOutput(true);  
    		connection.setDoInput(true);  
    		connection.setUseCaches(false);  
    		connection.setInstanceFollowRedirects(true);  
    		connection.setRequestMethod("POST"); // 设置请求方式  
    		connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
    		connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
    		connection.connect();  
    		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码  
    		out.append(jsonStr);  
    		out.flush();  
    		out.close();  
    		
    		int code = connection.getResponseCode();  
    		InputStream is = null;  
    		if (code == 200) {  
    			is = connection.getInputStream();  
    		} else {  
    			is = connection.getErrorStream();  
    		}  
    		
    		// 读取响应  
    		int length = (int) connection.getContentLength();// 获取长度  
    		if (length != -1) {  
    			byte[] data = new byte[length];  
    			byte[] temp = new byte[512];  
    			int readLen = 0;  
    			int destPos = 0;  
    			while ((readLen = is.read(temp)) > 0) {  
    				System.arraycopy(temp, 0, data, destPos, readLen);  
    				destPos += readLen;  
    			}  
    			String result = new String(data, "UTF-8"); // utf-8编码  
    			return result;  
    		}  
    		
    	} catch (IOException e) {  
    		e.printStackTrace();
    	}  
    	return "error"; // 自定义错误信息  
    }  
    
    public static String getJsonData(JSONObject jsonParam,String urls) {  
        StringBuffer sb=new StringBuffer();  
        try {  
            ;  
            // 创建url资源  
            URL url = new URL(urls);  
            // 建立http连接  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            // 设置允许输出  
            conn.setDoOutput(true);  
            // 设置允许输入  
            conn.setDoInput(true);  
           // 设置不用缓存  
            conn.setUseCaches(false);  
           // 设置传递方式  
            conn.setRequestMethod("POST");  
           // 设置维持长连接  
            conn.setRequestProperty("Connection", "Keep-Alive");  
           // 设置文件字符集:  
            conn.setRequestProperty("Charset", "UTF-8");  
           // 转换为字节数组  
            byte[] data = (jsonParam.toString()).getBytes();  
          // 设置文件长度  
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
          // 设置文件类型:  
            conn.setRequestProperty("contentType", "application/json");  
            // 开始连接请求  
            conn.connect();        
            OutputStream out = new DataOutputStream(conn.getOutputStream()) ;  
            // 写入请求的字符串  
            out.write((jsonParam.toString()).getBytes());  
            out.flush();  
            out.close();  
  
            System.out.println(conn.getResponseCode());  
              
            // 请求返回的状态  
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){  
                System.out.println("连接成功");  
                // 请求返回的数据  
                InputStream in1 = conn.getInputStream();  
                try {  
                      String readLine=new String();  
                      BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));  
                      while((readLine=responseReader.readLine())!=null){  
                        sb.append(readLine).append("\n");  
                      }  
                      responseReader.close();  
                      System.out.println(sb.toString());  
                      
                } catch (Exception e1) {  
                    e1.printStackTrace();  
                }  
            } else {  
                System.out.println("error++");  
                  
            }  
  
        } catch (Exception e) {  
  
        }  
          
        return sb.toString();  
  
    }  
    
    
    public static String formPost(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "cecook-boundary";
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					String filename = file.getName();
					String contentType = new MimetypesFileTypeMap().getContentType(file);
					if (filename.endsWith(".gif")) {
						contentType = "image/gif";
					}
					if (filename.endsWith(".jpeg") || filename.endsWith(".jpeg") || filename.endsWith(".jpg")) {
						contentType = "image/jpeg";
					}
					if (filename.endsWith(".png")) {
						contentType = "image/png";
					}
					if (filename.endsWith(".bmp")) {
						contentType = "application/x-bmp";
					}
					if (contentType == null || contentType.equals("")) {
						contentType = "application/octet-stream";
					}

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
					out.write(strBuf.toString().getBytes());
					DataInputStream in = new DataInputStream(new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			System.out.println("send POST request error:" + urlStr);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}
}
